<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Cookbook;
use Dingo\Api\Http\Request;

class CookbookController extends BaseController
{

    public $model = Cookbook::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $title = $request->input('title');
        $category_id = $request->input('category_id');
        $contact = $request->input('contact');
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');
        $status = $request->input('status');
        $order_by_key = $request->input('order_by_key', 'sort');
        $order_by_value = $request->input('order_by_value', 'desc');
        $is_on = $audit_status = -1;
        if ($status == 1) {
            $audit_status = 0; //待审核
        } else if($status == 2) {
            $is_on = 1; //上架
        } else if($status == 3) {
            $is_on = 0; //下架
        }

        $price_type = $request->input('price_type');
        $is_vip = $request->input('is_vip', -1);
        $is_free = -1;
        if ($price_type == 1) {
            $is_free = 1; //免费
        } else if($price_type == 2) {
//            $is_vip = 1; //会员专属
        } else if($price_type == 3) {
            $is_free = 0; //收费
        }

        $users = Cookbook::title($title)
            ->startAt($start_at)
            ->endAt($end_at)
            ->category($category_id)
            ->with('category')
            ->isOn($is_on)->auditStatus($audit_status)->when($is_free != -1, function ($q)use($is_free) {
                $q->where('is_free', '=', $is_free);
            })->when($is_vip != -1, function ($q)use($is_vip) {
                $q->where('is_vip', '=', $is_vip);
            })->when($contact, function ($q) use($contact){
                $q->whereHas('merchant', function ($query) use($contact){
                    $query->where('contact', 'like',  '%' . $contact . '%');
                });
            })->orderBy($order_by_key, $order_by_value)->orderBy("id", "desc")
                ->paginate(\request('per_page', 20));

        return $this->paginate($users);
    }

}

